package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.lulian.gxmh.dto.GxmhEnterpriseSearchParamDto;
import com.aiti.lulian.gxmh.dto.GxmhEnterpriseSearchResultDto;
import com.aiti.lulian.gxmh.dto.GxmhToCardInfoDto;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.service.GxmhEnterpriseSearchService;
import com.aiti.lulian.gxmh.vo.GxmhEnterpriseSearchResultVo;
import com.aiti.lulian.mapper.gxmh.GxmhEnterpriseMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.mapper.gxmh.GxmhTempMapper;
import com.aiti.lulian.utils.BusinessUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-06-10 14:18
 **/
@Service
@Slf4j
public class GxmhEnterpriseSearchServiceImpl implements GxmhEnterpriseSearchService {

    @Autowired
    private GxmhEnterpriseMapper gxmhEnterpriseMapper;
    @Autowired
    private GxmhYzqyDataCacheManage gxmhYzqyDataCacheManage;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private GxmhTempMapper gxmhTempMapper;


    /**
     * 工信门户--优质企业搜索
     * 需求：根据名片的访问次数降序排序，取出前100条，每天前10页随机显示排序前100条的数据。从第11页开始正常显示
     * 实现：定时任务每天取前100条数据，打乱顺序后放入缓存。
     *  1. 如果请求只有分页条件且页数在前10页，则从缓存中获取数据
     *  2. 如果请求分页条件页数大于10，则从数据库中获取数据
     *  3. 如果有其他查询条件，则从数据库中获取数据
     * @param queryDto
     * @return
     */
    public PageResult<GxmhEnterpriseSearchResultVo> gxmhEnterpriseSearch(GxmhEnterpriseSearchParamDto queryDto, String userId, String countyAreaCode) {
        BusinessUtil.checkPageParam(queryDto);
        // 判断是否除了分页参数之外的查询条件是否为空，如果为空且缓存数据存在，则直接返回缓存数据
        if(BusinessUtil.allPropertiesEmpty(queryDto) && queryDto.getPageNum() <= 10) {
            // 在缓存中取数据并返回
            if(gxmhYzqyDataCacheManage.yzqyCacheDataExist()) {
                List<GxmhEnterpriseSearchResultDto> yzqyData = gxmhYzqyDataCacheManage.getYzqyData(queryDto.getPageNum(), queryDto.getPageSize());
                //---------------------- 临时处理，判断如果当前区县参数是安丘市的，则将前九条数据替换为固定的企业数据----------
                if(StrUtil.isNotBlank(countyAreaCode) && "46A7A9EA-B0B7-4637-9484-78E78D2DCEA4".equals(countyAreaCode) && queryDto.getPageNum() == 1) {
                    List<GxmhEnterpriseSearchResultDto> anQiuShiData = gxmhTempMapper.queryEnterpriseInfo();
                    if(CollectionUtil.isNotEmpty(anQiuShiData)) {
                        for(int i = 0; i < anQiuShiData.size(); i++) {
                            yzqyData.set(i, anQiuShiData.get(i));
                        }
                    }
                }
                //------------------------ 临时处理结束-----------------------------------------------------------
                List<GxmhEnterpriseSearchResultVo> voList = this.convertResult(yzqyData);
                this.setToCardInfo(voList);
                // 前端暂时没有用到数据总数，先设置100与缓存的数据量一致
                PageResult<GxmhEnterpriseSearchResultVo> pageResult = new PageResult<>(voList, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), 100);
                return pageResult;
            }
        }
        this.dealSearchParam(queryDto);
        IPage<GxmhEnterpriseSearchResultDto> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhEnterpriseSearchResultDto> resultDtoList = gxmhEnterpriseMapper.queryEnterpriseInfo(page, queryDto);
        List<GxmhEnterpriseSearchResultVo> voList = this.convertResult(resultDtoList);
        this.setToCardInfo(voList);
        PageResult<GxmhEnterpriseSearchResultVo> pageResult = new PageResult<>(voList, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 工信门户--小程序首页企业库
     * enterpriseType: 1:专精特新   2：小巨人  3：瞪羚
     * @return
     */
    public List<GxmhEnterpriseSearchResultVo> queryIndexEnterpriseInfo(Integer enterpriseType) {
        if(enterpriseType == null || enterpriseType < 1 || enterpriseType > 3) {
            return new ArrayList<>();
        }
        List<GxmhEnterpriseSearchResultVo> voList = gxmhEnterpriseMapper.queryIndexEnterpriseInfo(enterpriseType);
        this.setToCardInfo(voList);
        return voList;
    }

    private List<GxmhEnterpriseSearchResultVo> convertResult(List<GxmhEnterpriseSearchResultDto> resultDtoList) {
        List<GxmhEnterpriseSearchResultVo> voList = new ArrayList<>(20);
        if(CollectionUtil.isEmpty(resultDtoList)) {
            return voList;
        }
        for(GxmhEnterpriseSearchResultDto resultDto : resultDtoList) {
            GxmhEnterpriseSearchResultVo vo = new GxmhEnterpriseSearchResultVo();
            vo.setEnterpriseId(resultDto.getEnterpriseId());
            vo.setEnterpriseName(resultDto.getEnterpriseName());
            vo.setLogo(resultDto.getLogo());
            String productPic = resultDto.getProductPic();
            if(StrUtil.isEmpty(productPic)) {
                vo.setProductPicList(new ArrayList<>());
            }else {
                vo.setProductPicList(StrUtil.split(productPic, ","));
            }
            List<String> qualificationTypeList = new ArrayList<>(10);
            if(1 == resultDto.getLead()) {
                qualificationTypeList.add("龙头企业");
            }
            if(1 == resultDto.getGazelle()) {
                qualificationTypeList.add("瞪羚企业");
            }
            if(1 == resultDto.getChampion()) {
                qualificationTypeList.add("单项冠军");
            }
            if(1 == resultDto.getSpecial()) {
                qualificationTypeList.add("专精特新");
            }
            if(1 == resultDto.getGiant()) {
                qualificationTypeList.add("小巨人企业");
            }
            if(1 == resultDto.getUnicorn()) {
                qualificationTypeList.add("独角兽企业");
            }
            if(1 == resultDto.getHightech()) {
                qualificationTypeList.add("高新技术企业");
            }
            vo.setQualificationTypeList(qualificationTypeList);

            voList.add(vo);
        }
        return voList;
    }

    private void dealSearchParam(GxmhEnterpriseSearchParamDto queryDto) {
        if(CollectionUtil.isEmpty(queryDto.getQualificationType())) {
            return;
        }
        for(String qualificationType : queryDto.getQualificationType()) {
            if("瞪羚企业".equals(qualificationType)) {
                queryDto.setGazelle(1);
            }
            if("单项冠军".equals(qualificationType)) {
                queryDto.setChampion(1);
            }
            if("专精特新".equals(qualificationType)) {
                queryDto.setSpecial(1);
            }
            if("小巨人企业".equals(qualificationType)) {
                queryDto.setGiant(1);
            }
            if("独角兽企业".equals(qualificationType)) {
                queryDto.setUnicorn(1);
            }
            if("高新技术企业".equals(qualificationType)) {
                queryDto.setHightech(1);
            }
            if("龙头企业".equals(qualificationType)) {
                queryDto.setLead(1);
            }
        }
    }

    // 设置跳转名片的信息，企业主账号的名片
    private void setToCardInfo(List<GxmhEnterpriseSearchResultVo> voList) {
        if(CollectionUtil.isEmpty(voList)) {
            return;
        }
        List<String> enterpriseIdList = voList.stream().map(GxmhEnterpriseSearchResultVo::getEnterpriseId).collect(Collectors.toList());
        List<GxmhToCardInfoDto> toCardInfoList = gxmhEnterpriseMapper.queryEnterpriseInfoByCreditCode(enterpriseIdList);
        for(GxmhEnterpriseSearchResultVo vo : voList) {
            for(GxmhToCardInfoDto toCardInfo : toCardInfoList) {
                if(vo.getEnterpriseId().equals(toCardInfo.getEnterpriseId())) {
                    vo.setUserId(toCardInfo.getUserId());
                    vo.setMobile(toCardInfo.getMobile());
                    break;
                }
            }
        }
    }

}
